<?php
namespace Frame;
final class Frame {
    public static function run() {
        //初始化字符集
        self::initCharset();
        //初始化配置文件
        self::initConfig();
        //初始化路由参数
        self::initRoute();
        //初始化常量目录设置
        self::initConst();
        //初始化类的加载
        self::initAutoLoad();
        //初始化请求分发
        self::initDispatch();
    }
    private static function initCharset() {
        header("Content-type: text/html; charset=utf-8");
    }

    private static function initConfig() {
        $GLOBALS['config'] = require_once(APP_PATH . 'Conf' . DS . 'config.php');

    }

    //初始化路由
    private static function initRoute()
    {
        $p = $GLOBALS['config']['default_platform'];
        $c = isset($_GET['c']) ? $_GET['c'] : $GLOBALS['config']['default_controller'];
        $a = isset($_GET['a']) ? $_GET['a'] : $GLOBALS['config']['default_action'];
        define('PLAT',$p);
        define('CONTROLLER',$c);
        define('ACTION',$a);
    }

    private static function initConst(){
        define('VIEW_PATH', APP_PATH . 'View'.DS);
        define('FRAME_PATH', ROOT_PATH .DS. 'Frame'.DS);

    }

    private static function initAutoLoad() {
        spl_autoload_register(function ($className) {
            //将空间中类名转换为真实路径
            $filename=ROOT_PATH.DS.str_replace('\\',DS,$className).'.class.php';
            //echo "<br>Trying to load: $className => $filename<br>";
            //如果类文件存在则包含
            if(file_exists($filename)) {
                require_once($filename);
            }
        });
    }

    private static function initDispatch() {
        //构建控制器类名
        $className='\\'.PLAT.'\\'.'Controller'.'\\'.CONTROLLER.'Controller';
        //构建控制器类的对象
        $controller = new $className();
        //调用方法
        $actionName=ACTION;
        $controller->$actionName();
    }
}
